import { createApp, toRaw } from 'vue'
import { createPinia, PiniaPluginContext } from 'pinia'
import App from './App.vue'
import 'element-plus/dist/index.css'
import { router } from './router'
// 导入所有ElementPlus图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './css/index.css'
import './css/backstage.css'
import './css/article.css'
import './css/effects02.css'
import 'highlight.js/styles/atom-one-dark.css'
import 'highlight.js/lib/common'
import hljsVuePlugin from '@highlightjs/vue-plugin'
import hljs from 'highlight.js';
// Pinia持久化
const __piniaKey = '__PINIAKEY__'
//定义兜底变量

type Options = {
    key?: string
}
//定义入参类型

//将数据存在本地
const setStorage = (key: string, value: any): void => {
    localStorage.setItem(key, JSON.stringify(value))
}

//存缓存中读取
const getStorage = (key: string) => {
    return (localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {})
}

//利用函数柯丽华接受用户入参
const piniaPlugin = (options: Options) => {
    //将函数返回给pinia  让pinia  调用 注入 context
    return (context: PiniaPluginContext) => {
        const { store } = context;
        const data = getStorage(`${options?.key ?? __piniaKey}-${store.$id}`)
        store.$subscribe(() => {
            setStorage(`${options?.key ?? __piniaKey}-${store.$id}`, toRaw(store.$state));
        })
        //返回值覆盖pinia 原始值
        return {
            ...data
        }
    }
}

// 创建 Pinia 实例
const pinia = createPinia()

pinia.use(piniaPlugin({
    key: "pinia"
}))
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}
// 挂载到 Vue 实例
app.use(pinia)
app.use(router)
// 引入代码高亮，并进行全局注册
app.use(hljsVuePlugin)
app.directive('highlight', function (el) {
    const blocks = el.querySelectorAll('pre code');
    blocks.forEach((block: any) => {
        hljs.highlightBlock(block)
        block.innerHTML = `<ol><li>${block.innerHTML.replace(/\n/g, `</li><li class="line">`)}</li></ol>`;
    })
})

//创建v-highlight全局指令
// app.directive('highlight', function (el) {
// 	let blocks = el.querySelectorAll('pre code');
// 	blocks.forEach((block) => {
// 		hljs.highlightBlock(block)
// 		// 从这开始是设置行号
// 		block.innerHTML = `<ol><li>${block.innerHTML.replace(/\n/g, `</li><li class="line">`)}</li></ol>`;
// 	})
// })
app.mount('#app')
